// -- main frame

const { app, BrowserWindow } = require('electron');
const electron = require('electron');
import * as fs from 'fs';

let mainWindow: any = null;

// -- process argv
let argv = process.argv;
if (argv.length < 4) {
    console.log(`Usage: eyeprotect -d directory -s secends`);
    process.exit(0);
}


let picDir: string, defaultSleep = 60;

for (let i = 0, j = argv.length; i < j; i++) {
    if (argv[i] == '-d') {
        picDir = argv[i + 1];
    }
    else if (argv[i] == '-s') {
        try {
            defaultSleep = parseInt(argv[i + 1]);
        } catch (e) {
            defaultSleep = 60;
        }
    }
}

app.on('ready', function () {
    const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
    mainWindow = new BrowserWindow({
        height: height,
        width: width,
        frame: false,
        resizable: false
    });

    mainWindow.loadURL('file://' + __dirname + '/app/index.html');

    mainWindow.on("closed", () => {
        mainWindow = null;
    });

    mainWindow.webContents.on('did-finish-load', function () {
        let params = '[]';
        if (picDir != undefined) {
            let pics: string[];
            pics = fs.readdirSync(picDir);
            let ps: any[] = [];
            pics.forEach((pic) => {
                let picname = pic.toLowerCase();
                if (picname.endsWith('.png') || picname.endsWith('.jpg')) {
                    let p = `file://${picDir}/${pic}`;
                    ps.push(`"${p}"`);
                }
            });
            params = '[' + ps.join(',') + ']';
        }
        mainWindow.webContents.executeJavaScript(`window.tick=${defaultSleep};adjustWnd(${width}, ${height}, ${params});`);
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== "darwin") {
        app.quit();
    }
});
